package com.uinnova.product.eam.service.es;

import com.uinnova.product.eam.comm.model.es.CEamListing;
import com.uinnova.product.eam.comm.model.es.EamListing;
import com.uino.dao.AbstractESBaseDao;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
@Slf4j
public class EamListingDao extends AbstractESBaseDao<EamListing, CEamListing> {

    private static final Long DEFAULT_DOMAIN_ID = 1L;

    @Override
    public String getIndex() {
        return "uino_eam_listing";
    }

    @Override
    public String getType() {
        return getIndex();
    }

    @PostConstruct
    public void init() {
        super.initIndex();
        this.updateEmptyDomainIdRecord();
    }

    private void updateEmptyDomainIdRecord() {
        try {
            RestHighLevelClient clientc = getClient();
            GetIndexRequest getRequest = new GetIndexRequest();
            getRequest.indices(getFullIndexName());
            boolean existIndex = clientc.indices().exists(getRequest, RequestOptions.DEFAULT);
            if (existIndex) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                boolQueryBuilder.filter(QueryBuilders.scriptQuery(new Script("doc['domainId'].length==0")));
                List<EamListing> list = this.getListByQuery(boolQueryBuilder);
                if (!CollectionUtils.isEmpty(list)) {
                    for (EamListing eamListing : list) {
                        eamListing.setDomainId(DEFAULT_DOMAIN_ID);
                    }
                    this.saveOrUpdateBatch(list);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
